package com.lpf.jdk;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Slf4j
// 每次生成动态代理类对象时,实现了InvocationHandler接口的调用处理器对象 
public class InvocationHandlerImpl implements InvocationHandler {

    // 这其实是业务实现类对象，用来调用具体的业务方法
    private Object target;

    // 通过构造函数传入目标对象
    public InvocationHandlerImpl(Object target) {
        this.target = target;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        log.error("使用jdk动态代理 开启事务");
        Object result = method.invoke(target, args);
        log.error("使用jdk动态代理 提交事务");
        return result;
    }

    public static void main(String[] args) throws Exception {

        MemberService memberServiceImpl = new MemberServiceImpl();
        InvocationHandlerImpl invocationHandlerImpl = new InvocationHandlerImpl(memberServiceImpl);

        ClassLoader loader = memberServiceImpl.getClass().getClassLoader();
        Class<?>[] interfaces = memberServiceImpl.getClass().getInterfaces();

        // 主要装载器、一组接口及调用处理动态代理实例
        MemberService newProxyInstance = (MemberService) Proxy.newProxyInstance(loader, interfaces, invocationHandlerImpl);
        newProxyInstance.memberAdd();
    }

}
